package com.app.piemoment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.app.piemoment.config.ApiConfig;
import com.app.piemoment.entity.LoginInfo;
import com.app.piemoment.entity.PackageCallback;
import com.app.piemoment.log.PMLog;
import com.app.piemoment.net.HttpResultJson;
import com.app.piemoment.net.NetService;
import com.app.piemoment.util.StringUtils;

public class RegeditActivity extends Activity {
	public int sex = 1;
	EditText sex_edittext, phone_edittext, email_edittext, repassword_edittext,
			password_edittext;
	SharedPreferences userInfo;
	Button ok_Button;
	String email;
	String phone;
	String password;
	String repassword;
	private String PREF_NAME = "PREF_NAME";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.regedit_info);

		userInfo = getSharedPreferences(PREF_NAME, MODE_WORLD_READABLE);

		// sex_EditText = (EditText) findViewById(R.id.sex_edittext);
		phone_edittext = (EditText) findViewById(R.id.phone_edittext);
		email_edittext = (EditText) findViewById(R.id.email_edittext);
		password_edittext = (EditText) findViewById(R.id.password_edittext);
		repassword_edittext = (EditText) findViewById(R.id.repassword_edittext);
		ok_Button = (Button) findViewById(R.id.ok_button);
		ok_Button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				email = email_edittext.getText().toString();
				phone = phone_edittext.getText().toString();
				password = password_edittext.getText().toString();
				repassword = repassword_edittext.getText().toString();
				if (StringUtils.isNullOrEmpty(email)
						|| StringUtils.isNullOrEmpty(phone)
						|| StringUtils.isNullOrEmpty(password)
						|| StringUtils.isNullOrEmpty(repassword)) {
					Toast.makeText(RegeditActivity.this, "信息输入不完整，请检查",
							Toast.LENGTH_LONG).show();
					return;
				}

				if (!StringUtils.isEmail(email)) {
					Toast.makeText(RegeditActivity.this, "邮箱输入有误！",
							Toast.LENGTH_LONG).show();
					return;
				}

				// if (!StringUtils.isPhoneNumberValid(phone)) {
				// Toast.makeText(RegeditActivity.this, "手机号码输入有误！",
				// Toast.LENGTH_LONG).show();
				// return;
				// }

				if (!StringUtils.isPassword(password)) {
					Toast.makeText(RegeditActivity.this, "密码输入有误！",
							Toast.LENGTH_LONG).show();
				}

				if (!password.equals(repassword)) {
					Toast.makeText(RegeditActivity.this, "两次密码不一致！",
							Toast.LENGTH_LONG).show();
					return;
				}
				userInfo.edit().putString("email", email).commit();
				userInfo.edit().putString("phone", phone).commit();
				userInfo.edit().putString("password", password).commit();
				RegAsy regAsy = new RegAsy();
				regAsy.execute();

			}
		});
		// sex_EditText.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		//
		// if (sex == 1) {
		// sex_EditText.setText("女");
		// sex = 0;
		// } else {
		// sex_EditText.setText("男");
		// sex = 1;
		// }
		//
		// }
		// });
		// birthday_EditText = (EditText) findViewById(R.id.birthday_edittext);
		// birthday_EditText.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// showDataSelect();
		//
		// }
		// });

	}

	public boolean checkEvething() {

		return true;
	}

	//
	// private void showDataSelect() {
	//
	// int year = 0;
	// int monthOfYear = 0;
	// int dayOfMonth = 0;
	// if (birthday_EditText != null) {
	// try {
	// String[] time = birthday_EditText.getText().toString().split(
	// "-");
	// year = Integer.parseInt(time[0]);
	// monthOfYear = Integer.parseInt(time[1]) - 1;
	// dayOfMonth = Integer.parseInt(time[2]);
	// } catch (Exception e) {
	// final Calendar c = Calendar.getInstance();
	// year = c.get(Calendar.YEAR);
	// // 获取当前年份
	// monthOfYear = c.get(Calendar.MONTH);// 获取当前月份
	// dayOfMonth = c.get(Calendar.DAY_OF_MONTH);// 获取当前月份的日期号码
	// }
	// }
	// new DatePickerDialog(RegeditActivity.this, dataSetListener, year,
	// monthOfYear, dayOfMonth).show();
	//
	// }
	//
	// private OnDateSetListener dataSetListener = new
	// DatePickerDialog.OnDateSetListener() {
	// @Override
	// public void onDateSet(DatePicker view, int year, int monthOfYear,
	// int dayOfMonth) {
	// String date = pad(year) + "-" + pad(monthOfYear + 1) + "-"
	// + pad(dayOfMonth);
	// birthday_EditText.setText(date);
	// }
	// };
	//
	// private String pad(int c) {
	// if (c >= 10)
	// return String.valueOf(c);
	// else
	// return "0" + String.valueOf(c);
	// }

	class RegAsy extends AsyncTask<Object, Object, LoginInfo> {
		ProgressDialog bDialog = ProgressDialog.show(RegeditActivity.this,
				"请稍候", "正在获取验证码");
		JSONObject jsonObject;
		PackageCallback packageCallback;

		@Override
		protected LoginInfo doInBackground(Object... param) {

			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("_format", "json"));
			params.add(new BasicNameValuePair(ApiConfig.DEFAULT_TOKENS,
					ApiConfig.DEFAULT_TOKEN_VALUE));
			params.add(new BasicNameValuePair("email", email_edittext.getText()
					.toString()));
			params.add(new BasicNameValuePair("mobile_phone", phone_edittext
					.getText().toString()));
			params.add(new BasicNameValuePair("passwd", password_edittext
					.getText().toString()));
			HttpResultJson result = NetService.httpPostReturnJson(
					RegeditActivity.this, ApiConfig.URL_ROOT
							+ ApiConfig.REG_URL, params);
			jsonObject = result.getJson();
			if (jsonObject == null) {
				packageCallback = (PackageCallback) new PackageCallback() {

					@Override
					public PackageCallback parseItem(JSONObject jsonObject) {

						return null;
					}
				};
				packageCallback.isError = true;
				packageCallback.errorMsg = "数据有误";
			} else {
				packageCallback = (PackageCallback) new PackageCallback() {

					@Override
					public PackageCallback parseItem(JSONObject jsonObject) {
						return null;
					}
				}.parse(jsonObject);
			}

			return null;
		}

		@Override
		protected void onCancelled() {
			bDialog.dismiss();
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(LoginInfo result) {
			bDialog.dismiss();

			if (packageCallback.status == null) {
				PMLog.e("errorMsg", "erroMsg is " + packageCallback.getErrorMsg());
				Toast.makeText(RegeditActivity.this,
						packageCallback.getErrorMsg(), Toast.LENGTH_LONG)
						.show();
			} else {
				Toast.makeText(RegeditActivity.this, "激活码已发送",
						Toast.LENGTH_LONG).show();

				Intent intent = new Intent();
				intent.putExtra("phone", phone_edittext.getText().toString());
				intent.setClass(RegeditActivity.this, ActiveActivity.class);
				startActivity(intent);
			}
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			bDialog.show();
			super.onPreExecute();
		}

		@Override
		protected void onProgressUpdate(Object... values) {
			super.onProgressUpdate(values);
		}

	}
}
